<template>
  <div class="dashboard-editor-container">
    <div class="chart-wrapper1">
      <el-row :gutter="10">
        <el-col :span="8">
          多媒体类型：
          <el-radio v-model="radio1" label="1" style="color:#2ca7e9">视频</el-radio>
          <el-radio v-model="radio1" label="2" disabled style="color:#2ca7e9">文字</el-radio>
          <el-radio v-model="radio1" label="3" disabled style="color:#2ca7e9">电话</el-radio>
        </el-col>
      </el-row>
    </div>
     <el-row class="main">
      <el-col :span="24" class="left-col">
        <el-card>
          <div slot="header" class="clearfix">
            <el-button style="float: left; padding: 3px 0" type="text" @click="this.evaluatingShow">六维评测✄</el-button>
            <!-- <el-button style="margin-left:4px; padding: 3px 0" type="text" @click="this.targetMaintenance">目标值维护
            </el-button> -->
            <!-- <el-button style="float: right; padding: 3px 0" type="text" @click="this.detailShow">详情>></el-button> -->
          </div>
          <div :style="{float:'left',width:'100%'}">
            <ve-radar :data="radarData" :settings="radarSettings" :extend="radarExtend" :data-empty="radarEmpty">
            </ve-radar>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row style="margin-top:20px">
      <el-col class="total-col">
        <el-card>
          <div slot="header" class="clearfix">
            <el-col>
              <el-button style="float: left; padding: 3px 0" type="text">话量趋势对比图</el-button>
            </el-col>
          </div>
          <el-form :model="form" size="mini" label-position="top" ref="form">
            <el-row style="height:100%;margin-bottom:20px;" :gutter="10">
              <el-col :span="3">
                <el-form-item label='开始时间：' prop="startTime">
                  <el-time-select style="width:100%" placeholder="起始时间" default-value="08:00" clearable
                    v-model="form.startTime" :picker-options="{
                            start: '08:00',
                            step: '00:30',
                            end: '20:00',
                            maxTime: form.endTime
                          }">
                  </el-time-select>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label='结束时间：' prop="endTime">
                  <el-time-select style="width:100%" placeholder="结束时间" default-value="12:00" clearable
                    v-model="form.endTime" :picker-options="{
                                start: '08:00',
                                step: '00:30',
                                end: '20:00',
                                minTime: form.startTime
                              
                              }">
                  </el-time-select>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label='间隔时间：' prop="timeInterval">
                  <el-select v-model="form.timeInterval" style="width:100%" filterable placeholder="请选择时间粒度">
                    <el-option v-for="item in timeIntervalList" clearable :key="item.value" :label="item.name"
                      :value="item.value" :disabled="item.disabled"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :lg="2" :md="3" class="searchBtnMarginTop">
                <el-button type="primary" icon="el-icon-search" :loading="loading" size="mini" @click="query">查询
                </el-button>
              </el-col>
              <el-col :lg="2" :md="3" class="searchBtnMarginTop">
                <el-button type='warning' size='mini' icon='el-icon-refresh' @click="clearForm('form')">重置</el-button>
              </el-col>
            </el-row>

            <el-row>
              <el-col class="div" style="width:100%;">
                <ve-histogram :data="histogramData1" :extend="histogramExtend1" :grid="grid"
                  :settings="histogramSettings1" :colors="histogramColors1" width="100%" height="420px"></ve-histogram>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
   

    <!-- <keep-alive>
      <component :is="dialogList.siteTendency" :option="dialogOptions"></component>
    </keep-alive> -->
    <!-- <keep-alive>
      <component :is="dialogList.targetValMain" :option="dialogOptionv" @refreshTable="queryModelChart"></component>
    </keep-alive> -->

    <el-dialog title="雷达图指标配置" :visible.sync="isChoose" @close="closeUser" width="70%" @open="openCreate"
      :close-on-click-modal="false" center>
      <div v-loading="loading">
        <div class="content">
          <el-card>
            <el-transfer :titles="['可选指标', '已选指标']" v-model="value1" :data="data" @change="handleChange"></el-transfer>
          </el-card>
          <div style="text-align:center;margin-top:20px">
            <el-button size="mini" @click="addType" type="primary">确认</el-button>
            <el-button size="mini" @click="reset">取消</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import echarts from 'echarts';
  import toolBox from "@/common/utils/toolBox";
  // import siteTendency from "./dialog/siteTendency";
  // import targetValMain from "./dialog/targetValMain";
  import veRadar from "v-charts/lib/radar";
  import veLine from "v-charts/lib/line";
  import veRing from "v-charts/lib/ring";
  import veHistogram from "v-charts/lib/histogram";
  import queryQueDetail from "@/message/siteManagement/queueDetail/query";
  import 'v-charts/lib/style.css';
  // 发送接口
  import request1 from "@/common/utils/requestYg";
  // 趋势对比图-电话  查询 
  import y007 from "@/message/siteManagement/queueOverview/y007";
  // 六维查询
  import y008 from "@/message/siteManagement/queueOverview/y008";
  //六维指标查询
  import dataQuery from '@/message/wfm/baseData/dictionaryManage/dictionaryQuery'
  import request from "@/common/utils/requestWFM";

  export default {
    name: '',
    components: {
      veRadar,
      veLine,
      veRing,
      veHistogram
    },
    data() {
      return {
        dictionaryOption: [],
        // dataZoom:[{type:'slider',show:true,yAxisIndex:[0],left:'93%',start:30,end:80},
        // {type:'inside',show:true,yAxisIndex:[0],start:30,end:80},
        // {start:0,end:100,height:20}],
        enum: {
          1: "当前排队数",
          2: "20s接通量",
          3: "人工总接通量",
          4: "接通率",
          5: "呼损数",
          6: "总进线量",
          7: "20s服务水平",
          8: "呼损率",
          9: "接通排队总时间",
          10: "接通平均排队时间",
          11: "呼损排队总时间",
          12: "呼损平均排队时间"
        },
        pollingPause: false, //暂停标记
        queryTimeSpace: 100000, //轮询时间间隔
        isChoose: false,
        dataQ: [],
        list2: [],
        list3: [],
        data: [],
        // data: generateData(),
        // value1: [1,7,4,3,6,5],
        // value1: [1, 2, 3, 4, 5, 6],
        value1Backup: [],
        value1: ['视频队列_接通率', '视频队列_平均振铃时长', '视频队列_20S服务水平', '视频队列_客户放弃率', '视频队列_平均排队时长', '视频队列_呼损率'],
        loading: false,
        options: {
          group: 'mission'
        },
        form1: {
          company: "",
          group: "",
          agentid: ""
        },
        teamList: [],
        companyList: [],
        currentPage: 1,
        //1页左上
        radarData: {
          columns: ['情况', '20S服务水平', '人工总接通量', '呼损率', '接通率', '客服放弃平均时长', '平均振铃时长'],
          rows: [],
        },
        radarEmpty: false,
        radarExtend: {
          series: {
            color: ['#147e88', '#409eff'],
            label: {
              show: false,
              position: 'insideRight',
              fontSize: 10,
              formatter: (params) => {
                return params.value
              },
            },
          },
          radar: {
            name: {
              // formatter:'{value}',
              formatter: (str) => {
                let val = this.radarData.rows[0][str];
                // let val1 = this.radarData.rows[1][str];
                if (val == undefined) {
                  val = 0
                }
                if (str == '客户放弃率' || str == '接通率' || str == '20S服务水平' || str == '呼损率') {
                  val = val * 100 + '%'
                } else {
                  val = this.secondFormat(val)
                }
                // if (val1 == undefined) {
                //   val1 = 0
                // }
                // return str + "\n" + `{b|${val}}` + ":" + `{c|${val1}}`
                return str + "\n" + `{b|${val}}`
              },
              textStyle: {
                fontSize: 15,
                color: '#000'
              },
              rich: {
                a: {
                  color: 'red',
                  align: 'center',
                  fontSize: 15,
                  padding: 2,
                },
                b: {
                  color: '#147e88',
                  align: 'center',
                  fontSize: 15,
                  padding: 2,

                },
                c: {
                  color: '#409eff',
                  align: 'center',
                  fontSize: 15,
                  padding: 2,

                },
              },
            },
            shape: "polygon",
          },
          // tooltip: {
          //   // trigger: 'axis',
          //   formatter: (params, ticket, callback) => {
          //     console.log('111111111',params);
          //     console.log('2222222',ticket);
          //     var showHtm = "";
          //     // for (var i = 0; i < params.length; i++) {
          //     //   //x轴名称
          //     //   var name = params[i][1];
          //     //   //名称
          //     //   var text = params[i][3];
          //     //   //值
          //     //   var value = params[i][2];
          //     //   showHtm += text + '--' + name + ' 得分：' + value + '<br>'
          //     // }
          //     return showHtm;
          //   }
          // },
          legend: {
            show: true,
            x: 'right',
            // y:'bottom',
          },
        },
        grid: {
          left: 20,
          right: 50
        },
        radarSettings: {
          areaStyle: ["#red"],
          dataType: {
            '客户放弃率': 'percent',
            '呼损率': 'percent',
            '接通率': 'percent',
            '20S服务水平': 'percent',
          },
        },
        histogramColors1: ['#ef5b9c', '#f5a286', '#c6a7f8', '#e1b737', '#409eff', 'green'],
        histogramData1: {
          columns: ['WORKTIME', '20S服务水平', '人工总接通量', '呼损率', '接通率', '客服放弃平均时长', '平均振铃时长'],
          rows: [
            // {'WORKTIME':'04:00','20s接通量':'0','人工总接通量':'0','呼损数':'0','接通率':'0','当前排队数':'0','总进线量':'0'},
          ]
        },

        histogramExtend1: {
          dataZoom: [{
            type: 'slider', //图表下方的伸缩条
            show: true, //是否显示
            //  　　　　realtime : true, //拖动时，是否实时更新系列的视图
            start: 0, //伸缩条开始位置（1-100），可以随时更改
            end: 100, //伸缩条结束位置（1-100），可以随时更改
          }],
          series: {
            // barWidth:4,
            barGap: "100%",
            // stack: '堆叠', //堆叠柱状图在此设置成统一名称即可  
            itemStyle: {
              normal: {
                label: {
                  show: false,
                  position: 'top',
                  textStyle: {
                    color: 'black',
                    fontSize: 9
                  }
                }
              }
            }
          },
          legend: {
            y: "top"
          }
        },
        histogramSettings1: {
          showLine: ["接通率", "20S服务水平", "呼损率", '客户放弃率'],
          axisSite: {
            right: ["接通率", "20S服务水平", "呼损率", '客户放弃率'],
          },
          yAxisType: ["normal", "percent"],
          yAxisName: ["话量", "比率"],
        },

        loading: false, //loading遮罩                                    
        radio1: "1",
        tableData1: [],
        totalRcrdNum: 0,
        timeIntervalList: [{
            name: "10分钟",
            value: "10"
          },
          {
            name: "15分钟",
            value: "15"
          },
          {
            name: "30分钟",
            value: "30"
          },
          {
            name: "60分钟",
            value: "60"
          },

        ],
        form: {
          timeInterval: "10",
          startTime: '08:00',
          endTime: '12:00',
        },

        dialogList: {
          // siteTendency,
          // targetValMain
        },
        dialogOptions: {
          isShow: false
        },
        dialogOptionv: {
          isShow: false
        },
        brnoList: [],
      }
    },
    computed: {},
    created() {
      this.dictionaryQuery()
      this.queryModelChart();
      this.query();
      // this.queryDetail();
      this.polling(true, true);
    },
    mounted() {
      this.brnoList = toolBox.formatTreeData(
        this.brnoList,
        "orgno",
        "superno"
      );
      // this.radarEmpty = (this.radarData.rows.length == 0);
    },
    watch: {
      radio1: function (newVal, oldVal) {
        this.chooseFormat();
        this.queryModelChart();
        this.query();
        this.queryDetail();
      },
    },
    methods: {
      // 秒格式化
      secondFormat(value) {
        return toolBox.formatSeconds(value)
      },
      // 数据字典
      async dictionaryQuery() {
        let resBody = new dataQuery();
        resBody.data.FIELDCODE = 'QUEUEPARA'
        // resBody.data.FIELDNAME = this.form.name;
        resBody.data.CurrPage = 1
        resBody.data.PageRowNum = 200
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.dictionaryOption = response.BODY.FIEDATA;
          let arr = response.BODY.FIEDATA;
          arr.forEach(item => {
            this.data.push({
              key: item.FIELDKEY,
              label: item.FIELDVALUE
            })
          })
          this.chooseFormat();
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      polling(ifQuery, ifLoop) {
        var vueIns = this;
        if (ifLoop) {
          this.queryTimeout = setTimeout(function () {
            var tagsArr = vueIns.$store.state.tagsView.cachedViews;
            var currentPageName = vueIns.$router.currentRoute.name;
            var thisPageName = "1010";
            if (tagsArr.indexOf(thisPageName) + 1) {
              //先判断标记
              if (vueIns.pollingPause) {
                vueIns.polling(false, true);
              } else if (currentPageName == thisPageName) {
                //在页签中且是当前页时发送
                ifQuery && vueIns.queryModelChart() && vueIns.query() && vueIns.queryDetail();
                vueIns.polling(true, true);
              } else if (currentPageName != thisPageName) {
                //在页签中有但不是当前页时 或暂停字段为true时 暂停发送请求
                ifQuery && vueIns.queryModelChart() && vueIns.query() && vueIns.queryDetail();
                vueIns.polling(false, true);
              } else {
                //未知情况下停止
                clearTimeout(vueIns.queryTimeout);
                vueIns.polling(false, false);
              }
            } else {
              //不在页签中时直接关闭
              clearTimeout(vueIns.queryTimeout); //其实不用这步
              vueIns.polling(false, false);
            }
          }, vueIns.queryTimeSpace);
        }
      },
      chooseFormat() {
        this.dataQ = [];
        for (let i = 0; i < this.value1.length; i++) {
          const element = this.enum[this.value1[i]];
          this.dataQ.push(element)
        }
        this.radarData.columns = ['情况']
        this.histogramData1.columns = ['WORKTIME'];
        for (let i = 0; i < this.value1.length; i++) {
          this.dictionaryOption.forEach(value => {
            if (value.FIELDKEY == this.value1[i]) {
              this.radarData.columns.push(value.FIELDVALUE)
              this.histogramData1.columns.push(value.FIELDVALUE);
            }
          })
        }
        // console.log("this.histogramData1.column", this.histogramData1.columns);
        // console.log("this.radarData.columns", this.radarData.columns);
      },
      closeUser() {
        //关闭弹窗清楚表单数据并清楚表单验证
        this.isChoose = false;
        this.value1 = JSON.parse(JSON.stringify(this.value1Backup))
        this.chooseFormat()
      },
      reset() {
        this.value1 = JSON.parse(JSON.stringify(this.value1Backup))
        this.isChoose = false
        this.chooseFormat();
      },
      addType() {
        if (this.value1.length != 6) {
          this.isChoose = true;
          this.$message.warning(`已选指标个数只能为六`);
        } else {
          this.value1Backup = JSON.parse(JSON.stringify(this.value1))
          this.isChoose = false;
          this.chooseFormat();
          this.queryModelChart();
          this.query()
        }
      },
      openCreate() {

      },
      handleChange(value, direction, movedKeys) {
        // this.value1Backup = JSON.parse(JSON.stringify(this.value1))
        this.value1 = value;
      },
      async queryModelChart() {
        let resBody = new y008();
        // resBody.data.type = "queue";
        // resBody.data.eleArr = this.dataQ;
        resBody.data.MONIKEY1 = this.value1[0]
        resBody.data.MONIKEY2 = this.value1[1]
        resBody.data.MONIKEY3 = this.value1[2]
        resBody.data.MONIKEY4 = this.value1[3]
        resBody.data.MONIKEY5 = this.value1[4]
        resBody.data.MONIKEY6 = this.value1[5]
        resBody.data.channel = this.radio1 == "1" ? "video" : this.radio1 == "2" ? "chat" : "voice";
        let response = await request1(resBody);
        var vueIns = this;
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.radarData.rows = [{
              '情况': '实际值'
            },
            // {
            //   '情况': '目标值'
            // }
          ];
          // this.list3 = response.RSP_BODY.struct[0].resultM;
          // this.list2 = response.RSP_BODY.struct[0].resultS;
          let list1 = response.RSP_BODY.detail[0]
          for (var p in list1) {
            //   // let a = p.split("-")[2];
            this.radarData.rows[0][p] = list1[p];
            //   this.radarData.rows[1][p] = this.list3[p];
          }
          // console.log('rows', this.radarData.rows)
          // console.log('columns', this.radarData.columns)
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" +
              response.SYS_HEAD.ReturnCode +
              "，错误信息：" +
              response.SYS_HEAD.ReturnMessage
          });
        }
      },
      // 队列详情查询
      queryDetail() {
        this.loading = true;
        let resBody = new queryQueDetail();

        request1(resBody)
          .then(response => {
            if (response.SYS_HEAD.ReturnCode === "000000") {
              this.tableData1 = response.RSP_BODY.QueueList || [];
              this.totalRcrdNum = response.RSP_BODY.RecordNum;
            } else {
              this.$message({
                type: "error",
                message: response.SYS_HEAD.ReturnMessage
              });
              // this.tableData1 = [];
              this.totalRcrdNum = 0;
            }
            this.loading = false;
          })
          .catch(error => {
            this.loading = false;
          })
      },
      detailShow(row, column, cell, event) {
        //debugger
        this.dialogOptions.isShow = true;
        this.dialogOptions.title = "队列详情";
        // this.dialogOptions.ODEDVSNLIST = this.ODEDVSNLIST;
      },
      targetMaintenance(row, column, cell, event) {
        //debugger
        this.dialogOptionv.isShow = true;
        this.dialogOptionv.title = "六维元素目标值维护";
        this.dialogOptionv.tableData = this.list3;
        // this.dialogOptions.ODEDVSNLIST = this.ODEDVSNLIST;
      },
      evaluatingShow(row, column, cell, event) {
        this.value1Backup = JSON.parse(JSON.stringify(this.value1))
        this.isChoose = true;
      },
      // 重置查询条件
      clearForm(item) {
        // 重置表格
        this.$refs["" + item].resetFields();
      },

      async query() {
        this.loading = true;
        let self = this;
        let resBody = new y007();
        resBody.data.CHANNEL = this.radio1 == "1" ? "video" : this.radio1 == "2" ? "online" : "voice";
        resBody.data.TIMEINTERVAL = this.form.timeInterval ? this.form.timeInterval : "10";
        resBody.data.STARTTIME = this.form.startTime ? this.form.startTime.replace(/\:/g, "") : "0800";
        resBody.data.ENDTIME = this.form.endTime ? this.form.endTime.replace(/\:/g, "") : "1200";
        resBody.data.MONIKEY1 = this.value1[0]
        resBody.data.MONIKEY2 = this.value1[1]
        resBody.data.MONIKEY3 = this.value1[2]
        resBody.data.MONIKEY4 = this.value1[3]
        resBody.data.MONIKEY5 = this.value1[4]
        resBody.data.MONIKEY6 = this.value1[5]
        request1(resBody)
          .then(response => {
            // 每次赋值前都要清除histogramData1.rows
            self.histogramData1.rows = [];
            if (response.SYS_HEAD.ReturnCode === "000000") {
              response.RSP_BODY.TRENDINFO.forEach(function (item, index, value) {
                item.WORKTIME = toolBox.timeFormat2Time(item.WORKTIME);
                self.histogramData1.rows.push(item);
              })
              // console.log("self.histogramData1.rows", self.histogramData1.rows);
              // console.log("self.histogramData1.columns", self.histogramData1.columns);
            } else if (response.SYS_HEAD.ReturnCode === "999999") {
              this.$message({
                type: "success",
                message: "该时间段无趋势数据"
              });
              // this.tableData=[];
            } else {
              this.$message({
                type: "error",
                message: response.SYS_HEAD.ReturnMessage
              });
              this.tableData = [];
            }
            this.loading = false;
          })
          .catch(error => {
            this.loading = false;
          });
      },
    }
  }

</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .el-table .cell {
    white-space: pre-line;
  }

  .right-col {
    height: 100%;
    background: #ffffff;
    margin-left: 20px;
    margin-top: 10px;
    // margin-bottom: 20px;
  }

  .div {
    height: 100%;
    background: #ffffff;
    // margin-top: 10px;
  }

  .left-col {
    height: 100%;
    background: #ffffff;
    margin-top: 10px;
  }

  .main1 {
    margin-bottom: 5px;
    height: 650px;
    background: #ffffff;
  }

  .main {
    margin-top:20px;
    margin-bottom: 5px;
    height: 100%;
    background: #f0f2f5;

    .total-col {
      width: 100%;
      // height: 100%;
      background: #ffffff;
    }

    .left-col {
      height: 100%;
      background: #ffffff;
    }

    .right-col {
      height: 100%;
      background: #ffffff;
      margin-left: 20px;
    }

    .el-card {
      height: 100%;
    }

    .linstyel {
      padding-top: 30px;
      height: 100%;
    }

    .main1 {
      height: 40%;
    }

    .main2 {
      height: 40%;
    }

    .class1 {
      margin-left: 20px;
      display: inline-block;
      width: 10px;
      height: 10px;
      //  border: 1px solid #2ca7e9;
      background-color: #2ca7e9;
    }

    .class2 {
      margin-left: 20px;
      display: inline-block;
      width: 10px;
      height: 10px;
      background-color: #19d4ae;
      //  border: 1px solid red;
    }
  }

  .dashboard-editor-container {
    height: 100%;
    padding: 16px;
    background-color: rgb(240, 242, 245);

    .chart-wrapper {
      background: #fff;
      padding: 16px 16px 0;
      margin-bottom: 32px;
    }

    .chart-wrapper1 {
      background: #f5f5f5;
      // padding: 16px 16px 0;
      margin-bottom: 2px;
      color: #2ca7e9;
    }

    .chart-wrapper2 {
      background: #fff;
      padding: 16px 16px 0;
      margin-bottom: 32px;

      height: 100%;
      float: left;
    }

    .a {
      float: right;

    }
  }

</style>
